<?php
declare(strict_types=1);

namespace WebApp\lib\db;

use ErrorException;
use MongoDB\Driver\Manager;
use PDO;
use SplQueue;
use Swoole\Coroutine\Mysql;
use Swoole\Mysql\Exception;

/**
 * Class MysqlPool
 * @package server\lib
 */
class MongoPool
{
    private $pool;
    public $useCo = true;

    private static $instance;

    /**
     * MysqlPool constructor.
     */
    private function __construct()
    {
//        if (ServerStation::$wId === null) {
//            $this->useCo = false;
//        } else {
//            $this->useCo = true;
//        }
        $this->useCo = false;
        $this->pool = new SplQueue;
    }

    

    /**
     *
     */
    public static function getInstance(){
        if(self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * @param Mysql|PDO $client
     */
    private function put($client)
    {
        $this->pool->push($client);
    }

    /**
     * @param $func
     * @return mixed
     */
    public function exec($func)
    {
        $client = $this->get();
        if (!$client) {
            return false;
        }
        try {
            $res = $func($client);
        } catch (ErrorException $e) {
            $res = false;
        } catch (Exception $e) {
            $res = false;
        }

        if ($res) {
            $this->put($client);
        }

        return $res;
    }

//    private $ip = "118.24.98.157";
    private $ip = "192.168.0.206";
    private $port = 28002;

    /**
     * @return Mysql|PDO
     */
    private function get()
    {
        if (count($this->pool) > 0) {
            return $this->pool->pop();
        }

        $ip = $this->ip;
        $port = $this->port;

        if (!$this->useCo) {
            $client = new Manager("mongodb://$ip:$port");
            $res = true;
        } else {
            $client = new Mysql();
//            $res = $client->connect(
//                [
//                    'host' => $ip,
//                    'user' => $user,
//                    'password' => $pwd,
//                    'database' => $dbName,
//                    'port' => $port,
//                    'timeout' => 2,
//                    'charset' => 'utf8mb4'
//                ]
//            );
            $res = true;
        }

        if ($res == false) {
            return null;
        } else {
            return $client;
        }
    }
}
